using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;

namespace CxRomos.Core.Services.Implementation {
    public class Cache {
        private static readonly System.Web.Caching.Cache cache;
        private static TimeSpan _timeSpan = new TimeSpan(Properties.CxRomos.Default.DefaultCacheDuration_Days,
                                                        Properties.CxRomos.Default.DefaultCacheDuration_Hours,
                                                        Properties.CxRomos.Default.DefaultCacheDuration_Minutes, 0);

        static Cache() {
            cache = HttpContext.Current.Cache;
        }

        public static object Get(string cacheKey) {
            return cache.Get(cacheKey);
        }

        public static List<string> GetCacheKeys() {
            var keys = new List<string>();
            var ca = cache.GetEnumerator();

            while(ca.MoveNext()) {
                keys.Add(ca.Key.ToString());
            }

            return keys;
        }

        public static void Set(string cacheKey, object cacheObject, DateTime expiration) {
            Set(cacheKey, cacheObject, expiration, CacheItemPriority.Normal);
        }

        public static void Set(string cacheKey, object cacheObject, DateTime expiration, CacheItemPriority priority) {
            cache.Insert(cacheKey, cacheObject, null, expiration, System.Web.Caching.Cache.NoSlidingExpiration, priority, null);
        }

        public static void Set(string cacheKey, object cacheObject, TimeSpan expiration, CacheItemPriority priority) {
            cache.Insert(cacheKey, cacheObject, null, System.Web.Caching.Cache.NoAbsoluteExpiration, expiration, priority, null);
        }

        public static void Delete(string cacheKey) {
            if(Exists(cacheKey) != null) {
                cache.Remove(cacheKey);
            }
        }

        private static object Exists(string cacheKey) {
            return cache[cacheKey] != null;
        }

        public static void Flush() {
            foreach (var key in GetCacheKeys()) {
                Delete(key);
            }
        }
    }
}